import { login, logout } from '@/api/common'
import { buildMenus } from '@/api/system/menu'
import {
  getToken,
  setToken,
  removeToken,
  getUserInfo,
  setUserInfo,
  removeUserInfo
} from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  userInfo: getUserInfo(),
  introduction: '',
  roles: '',
  rolesBtnMenu: '',
  changePwd: false
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_ROLES_BTN_MENU: (state, roles) => {
    state.rolesBtnMenu = roles
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  OPEN_CHANGE_PWD: (state, open) => {
    state.changePwd = open
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { userName, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: userName.trim(), password: password })
        .then(({ token, user, avatar, code, message }) => {
          if (token) {
            commit('SET_TOKEN', token)
            setToken(token)
          }
          // commit('SET_USER_INFO', { name: user.user.username, avatar, userId: user.user.id })
          commit('SET_USER_INFO', user.user)
          // setUserInfo({ name: user.user.username, avatar, userId: user.user.id })
          setUserInfo(user.user)
          resolve({ token, code, message })
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    // return new Promise((resolve, reject) => {
    //   const data = {}
    //   commit('SET_ROLES', ['admin'])
    //   data.roles = ['admin']
    //   resolve(data)
    // })
    return new Promise((resolve, reject) => {
      buildMenus(state.token)
        .then(({ list }) => {
          if (!list) {
            reject('登录失效，请重新登录。')
          }
          const rolesArry = []
          const rolesMenuArray = []
          list.forEach(el => {
            if (!el.hidden) rolesArry.push(el.path)
            if (el.children && el.children.length) {
              el.children.forEach(v => {
                if (!v.hidden) rolesArry.push(v.path)
                if (v.children && v.children.length > 0) {
                  v.children.forEach(m => {
                    if (!m.hidden) {
                      rolesArry.push(m.permission)
                      rolesMenuArray.push(m.permission)
                    }
                  })
                }
              })
            }
          })
          commit('SET_ROLES', rolesArry)
          commit('SET_ROLES_BTN_MENU', rolesMenuArray)
          // roles must be a non-empty array
          if (!list || list.length <= 0) {
            reject('该账号当前无任何权限，请联系管理员。')
          }
          resolve({ roles: rolesArry })
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_ROLES_BTN_MENU', [])
          commit('SET_USER_INFO', {})
          removeUserInfo()
          removeToken()
          resetRouter()
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_ROLES_BTN_MENU', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      const token = role + '-token'

      commit('SET_TOKEN', token)
      setToken(token)

      const { roles } = await dispatch('getInfo')

      resetRouter()

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/generateRoutes', roles, {
        root: true
      })

      // dynamically addOrEdit accessible routes
      router.addRoutes(accessRoutes)

      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, { root: true })

      resolve()
    })
  },
  toggleChangePwd({ commit }, open) {
    console.log(open)
    commit('OPEN_CHANGE_PWD', open)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
